import json
import requests
from urllib.parse import quote
from flask import jsonify, redirect, request, render_template
from .setting import *
from . import app_openid

@app_openid.route('/get_authorize_url')
def get_authorize_url():
    # 你的appid
    app_id = APPID
    # 你的回调路径
    back_url = BACKURL
    authorize_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + app_id + '&redirect_uri=' + back_url + \
          '&response_type=code&scope=snsapi_base#wechat_redirect'
    # print(url)
    return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody':{
                    'authorize_url' : authorize_url
                }
            }

@app_openid.route('/openid_callback', methods=['GET', 'POST'])
def openid_callback():
    data = request.args
    msg = data.get('msg')
    code = data['code'] if 'code' in data else None
    if not code:
        return redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx90014a2b7a9ab7f2&redirect_uri=http%3A//www.gogok12.com/api/v3/openid_callback&response_type=code&scope=snsapi_base&connect_redirect=1#wechat_redirect")

    # 你的appid,appsecret
    app_id ,app_key = APPID, APPKEY
    
    url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + app_id + '&secret=' + app_key + '&code=' + code + '&grant_type=authorization_code'
    r = requests.get(url)
    res = json.loads(r.text)
    open_id = res["openid"]

    return render_template('register.html', openid = open_id, msg = msg)
    # jsonify({'code': 200, 'open_id':open_id})